package com.zxy.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    private static final DateTimeFormatter fullFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String text = p.getValueAsString();
        if (text == null || text.isEmpty()) {
            return null;
        }
        
        try {
            // 尝试解析完整格式（包含秒）
            return LocalDateTime.parse(text, fullFormatter);
        } catch (Exception e) {
            try {
                // 如果完整格式解析失败，尝试不完整格式（不包含秒）
                return LocalDateTime.parse(text, formatter);
            } catch (Exception ex) {
                throw new IOException("Cannot parse LocalDateTime: " + text, ex);
            }
        }
    }
}
